package timex

import (
	"time"
)

const (
	FormatTime  = "2006-01-02 15:04:05"
	DefaultTime = "1000-01-01 00:00:00"
)

// TimeToDateString @Converter explicit:date
func TimeToDateString(t time.Time) string {
	return t.Format("2006-01-02")
}

// TimeToDateTimeString @Converter implicit:dateTime
func TimeToDateTimeString(t time.Time) string {
	return t.Format("2006-01-02 15:04:05")
}

func UnixNano() int64 {
	return time.Now().UnixNano()
}

func Unix() int64 {
	return time.Now().Unix()
}

func Now() time.Time {
	return time.Now()
}

// ParseDate @Converter explicit:date
func ParseDate(str string) time.Time {
	t, err := time.ParseInLocation("2006-01-02", str, time.Local)
	if err != nil {
		return time.Time{}
	}
	return t
}

// ParseDateTime @Converter implicit:dateTime
func ParseDateTime(str string) time.Time {
	t, err := time.ParseInLocation("2006-01-02 15:04:05", str, time.Local)
	if err != nil {
		return time.Time{}
	}
	return t
}

// ParseDateEnd @Converter explicit:dateEnd
func ParseDateEnd(str string) time.Time {
	t, err := time.ParseInLocation("2006-01-02", str, time.Local)
	if err != nil {
		return time.Time{}
	}
	return t.Add(24 * time.Hour).Add(-1 * time.Second)
}

func BeforeHour(h int64) time.Time {
	now := time.Now() //获取当前时间
	add := now.Add(time.Hour * -time.Duration(h))
	return add
}

func BeforeMinute(t int64) time.Time {
	now := time.Now() //获取当前时间
	add := now.Add(time.Minute * -time.Duration(t))
	return add
}

func CostTime(start, end string) int64 {
	if end == DefaultTime {
		end = time.Now().Format(FormatTime)
	}
	_start, _ := time.Parse(FormatTime, start)
	_end, _ := time.Parse(FormatTime, end)
	return _end.Unix() - _start.Unix()
}
